package cn.summit.tools;

import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.impl.DefaultMapperFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * bean对象之间copy
 *
 * @author summit
 * @since 2019/6/26 18:45
 */
public class BeanCopyUtils {

    /**
     * 跳过null
     */
    private static final MapperFacade MAPPER_FACADE = new DefaultMapperFactory.Builder()
            .mapNulls(false).build().getMapperFacade();


    private static final MapperFacade MAPPER_FACADE1 = new DefaultMapperFactory.Builder().build()
            .getMapperFacade();


    public static <T> T copy(Object source, Class<T> target) {
        if (source == null) {
            return null;
        }
        return MAPPER_FACADE1.map(source, target);
    }

    public static <T> void copy(Object source, Object target) {
        MAPPER_FACADE1.map(source, target);
    }

    public static <T> void copyExNull(Object source, Object target) {
        MAPPER_FACADE.map(source, target);
    }


    public static <T> List<T> copyCollection(List<?> objs, Class<T> clazz) {
        if (objs == null) {
            return null;
        }
        List<T> list = new ArrayList<>(objs.size());
        for (Object obj : objs) {
            if (obj == null) {
                return null;
            }
            list.add(MAPPER_FACADE1.map(obj, clazz));
        }

        return list;
    }
}
